<template>
    <nly-content-wrapper>
        <nly-content-header>
            <nly-row class="col-12 ">
                <nly-row class="col-12 ">
                    <nly-col xs="12" sm="12" md="12" lg="9" xl="9" class="form-inline " style="justify-content: left;">
                        <i :class="this.$route.meta.icon + ' text-info'" class="icon" /><span s>{{this.$route.name}}</span>
                    </nly-col>
                    <nly-col xs="12" sm="12" md="12" lg="3" xl="3" class="form-inline align-self-start" style="justify-content: right;">
                        <nly-button-group>
                            <nly-button variant="info" @click="PageList" button-class="mr-2">查询</nly-button>
                            <nly-button variant="info" button-class="mr-2" @click="reset">重置</nly-button>
                            <nly-button variant="info" @click="AddItem" button-class="mr-2">添加</nly-button>
                            <nly-button @click="showFunction" variant="info" button-class="mr-2"><i :class="show ? 'fas fa-angle-down mr-1' : 'fas fa-angle-up mr-1'" />{{ show ? "折叠" : "展开" }}</nly-button>
                        </nly-button-group>
                    </nly-col>
                </nly-row>

                <nly-row class="ml-1 mb-2 lr mt-4" v-show="show">
                    <nly-col xs="12" sm="12" md="12" lg="12" xl="12" class="form-inline " style="justify-content: left;">
                        <form-input title="字典标签" id="name" labelStyle="" rightStyle="width:120px;" class="ml-2" v-show="show" v-model="postData.dictLabel"></form-input>
                        <form-input title="字典键值" id="name" labelStyle="" rightStyle="width:120px;" class="ml-2" v-show="show" v-model="postData.dictValue"></form-input>
                        <form-select title="系统字典" class="ml-2" rightStyle="width:120px;" v-show="show" v-model="postData.isSys" :dataList="[
                  { key: 1, title: '是' },
                  { key: 0, title: '否' }
                ]"></form-select>
                        <form-select title="状态" class="ml-2" rightStyle="width:120px;" v-show="show" v-model="postData.status" :dataList="[
                  { key: 0, title: '正常' },
                  { key: 2, title: '停用' }
                ]"></form-select>
                    </nly-col>
                </nly-row>
            </nly-row>

            <nly-container fluid>
            </nly-container>
        </nly-content-header>
        <div class="tabpanel_tab_spacer"></div>
        <nly-content>
            <!-- 列表 -->
            <a-table :columns="columns" :components="components" :data-source="data" :scroll="{ y: 500}" bordered :pagination="false" :expandedRowKeys="expandedRowKeys" @expand="onTableExpand">
            </a-table>
            <!-- modal 弹窗  -->
            <a-modal :visible="editModal" lg :footer="null" :title="editItem.id ? '编辑' : '新增'" size="xl" @cancel="hideModal">
                <div class="form-inline mb-2">

                    <nly-col xs="12" sm="6" md="6" lg="4" xl="4">
                        <input-group-search v-model="editItem.parentId" title="上级字典" rightClass="col" treeType="dictData" :queryObj="{dictTypeId}"></input-group-search>
                    </nly-col>

                    <nly-col xs="12" sm="6" md="6" lg="4" xl="4">
                        <form-input title="字典标签" rightClass="col" v-model="editItem.dictLabel" labelStyle=""></form-input>
                    </nly-col>

                    <nly-col xs="12" sm="6" md="6" lg="4" xl="4">
                        <form-input title="字典键值" rightClass="col" v-model="editItem.dictValue" labelStyle=""></form-input>
                    </nly-col>
                    <nly-col xs="12" sm="6" md="6" lg="4" xl="4">
                        <form-input title="排序号" rightClass="col" v-model="editItem.treeSort" labelStyle=""></form-input>
                    </nly-col>

                    <nly-col xs="12" sm="6" md="6" lg="4" xl="4">
                        <form-radio title="系统内置" rightClass="col" v-model="editItem.isSys" :dataList="[
                { key: true, title: '是' },
                { key: false, title: '否' }
              ]"></form-radio>
                    </nly-col>

                    <nly-col xs="12" sm="6" md="6" lg="4" xl="4">
                        <form-input title="字典描述" rightClass="col" v-model="editItem.description" labelStyle=""></form-input>
                    </nly-col>
                    <nly-col xs="12" sm="6" md="6" lg="4" xl="4">
                        <form-input title="CSS样式" rightClass="col" v-model="editItem.cssStyle" labelStyle=""></form-input>
                    </nly-col>
                    <nly-col xs="12" sm="6" md="6" lg="4" xl="4">
                        <form-input title="CSS样式" rightClass="col" v-model="editItem.cssClass" labelStyle=""></form-input>
                    </nly-col>

                </div>

                <div class="form-inline mb-2">
                    <nly-col>
                        <!-- FormTextArea -->
                        <form-text-area title="备注信息" rightClass="col" v-model="editItem.remarks"></form-text-area>
                    </nly-col>
                </div>

                <nly-row style="justify-content: flex-end;">
                    <nly-button class="mt-3 mr-3" @click="onSubmit" variant="info">保存</nly-button>
                    <nly-button class="mt-3" variant="outlineDanger" @click="hideModal">关闭</nly-button>
                </nly-row>
            </a-modal>
        </nly-content>
    </nly-content-wrapper>
</template>

<script>

import { keyList, keySave, keyDelete, keyDisable, keyEnable } from "@/api/dictData";
import { listToMap } from "@/utils/tool/map";
import { pageListToTree } from "@/utils/tree";
import { components } from "@/utils/antTableComponents";

const basePostData = {
    "page.current": 1,
    "page.size": 1000,
    dictName: "",
    dictType: "",
    isSys: null,
    status: null
}
export default {
    //  components:{
    //     //注册：函数式组件
    //     MenuTabs: {
    //       functional: true,
    //       render: (h, ctx) => ctx.props.menuTabs
    //     }
    //  },

    data () {

        const columns = [{
            title: "字典标签",
            dataIndex: "dictLabel",
            key: "dictLabel",
            width: 120,
            align: "left",
            customRender: (text, row, index) => {
                return (
                    <span>
                        <a href="javascript:;" onClick={() => this.showModal(row)}>
                            {text}
                        </a>
                    </span>
                );
            }
        },
        {
            title: "字典键值",
            dataIndex: "dictValue",
            key: "dictValue",
            width: 120
        },
        {
            title: "排序",
            dataIndex: "treeSort",
            key: "treeSort",
            width: 80
        },
        {
            title: "系统字典",
            dataIndex: "isSys",
            key: "isSys",
            width: 80,
            customRender: (text, row, index) => {
                return text ? "是" : <span style="color:#aaa;">否</span>;
            }
        },
        {
            title: "更新时间",
            dataIndex: "createDate",
            key: "createDate",
            width: 150,
        },
        {
            title: "备注",
            dataIndex: "remarks",
            key: "remarks",
            width: 150
        },
        {
            title: "状态",
            dataIndex: "status",
            key: "status",
            width: 50,
            customRender: (text, row, index) => {
                return text == 2 ? <nly-badge bg-variant="danger">停用</nly-badge> : <nly-badge bg-variant="success">正常</nly-badge>;
            }
        },
        {
            title: "操作",
            dataIndex: "o",
            width: 200,
            key: "o",
            customRender: (text, row, index) => {
                return (<div class="row justify-content-md-center">
                    <span class="col"></span>
                    <span class="col-sm-auto col-md-auto col-lg-auto col-xl-auto">
                        <a href="javascript:;" title="编辑" class="mr-1 col-1" onClick={() => this.showModal(row)}><i class="fa fa-edit" style="color: #69aa46;"></i></a>
                        {row.status == 2 ? <a href="javascript:;" title="启用" class="mr-1 col-1" onClick={() => this.Enable(row)}><i class="fa fa-check-circle" style="color: #69aa46;"></i></a>
                            : <a href="javascript:;" title="禁用" class="mr-1 col-1" onClick={() => this.Disable(row)}><i class="fas fa-ban" style="color: #dd5a43;"></i></a>}
                        {row.treeLeaf ? <a href="javascript:;" title="删除" class="mr-1 col-1" onClick={() => this.DeleteItem(row)}><i class="fa fa-trash-alt" style="color: #dd5a43;"></i></a> : null}
                    </span>
                    <span class="col"></span>
                </div>);

            }
        }
        ];


        //表格 头部 可伸缩
        this.components = components(columns);
        return {
            dictTypeId: null,
            dictName: "",
            postData: { ...basePostData },
            numberReg: /^[1-9]{1}[0-9]*$/,
            floatReg: /^-?[0-9]*(\.[0-9]*)?$/,
            expandedRowKeys: [],
            haveExpandSet: new Set(),
            dataKeySet: new Set(),
            dataList: new Array(),
            data: [],
            columns,
            pagination: {
                defaultPageSize: 10,
                current: 1,
                pageSize: 10,
                total: 0,
                showTotal: total => `共 ${total} 条数据`,
                showSizeChanger: true,
                showQuickJumper: true,
                pageSizeOptions: ['10', '20', '30', '40', '50'],
            },
            breadcrumbItem: null,         //导航栏
            show: false,             //是否显示
            editItem: {},           //新增/编辑对象
            hideModal: false,
        };
    },
    created () {
        let { dictTypeId, dictName } = this.$route.params;
        console.log("dictData____created", this.$route.params);
        Object.assign(this, {
            dictTypeId,
            dictName
        });

        const breadcrumbItem = [
            {
                text: "首页",
                to: "/",
                icon: "nlyfont nly-icon-home-fill"
            },
            {
                text: "系统管理",
                to: "/system"
            },
            {
                text: "字典管理(" + this.dictName + ")",
                to: "/system/dictType/list",
                active: true
            }
        ];
        this.breadcrumbItem = breadcrumbItem;


    },
    mounted () {
        this.PageList();
    },
    computed: {
        parentItem: function () {
            const map = new Map();
            map.set(this.editItem.parentId, "");
            return map;
        },

    },
    methods: {
        //添加
        AddItem () {
            let { dictTypeId, dictName } = this;
            let arr = dictName.split(":");
            let dictType = arr[1];
            this.editItem = { dictTypeId, dictType };
            this.editModal = true;
        },
        //删除
        DeleteItem (menu) {
            let _this = this;
            this.$confirm({
                title: '提示',
                content: '您确定要删除该字典吗？',
                onOk () {
                    keyDelete({ id: menu.id })
                        .then(response => {
                            if (response.code === 200) {
                                _this.$message.success("删除成功");
                                //刷新 列表
                                _this.PageList();
                            }
                        });
                },
                onCancel () {
                },
            });
        },
        // 获取列表
        PageList () {
            const { postData, dictTypeId } = this;
            if (!dictTypeId) {


                return false;
            }

            Object.assign(postData, {
                dictTypeId
            })
            keyList(postData)
                .then(response => {
                    console.log("获取字典shuju列表", response);
                    if (response.code === 200) {
                        const { data } = response;
                        const { records, total, current, size } = data;
                        this.dataList = records;
                        this.haveExpandSet.clear();
                        this.dataKeySet.clear();
                        this.dataKeySet = new Set(records.map(f => f.id));
                        const childrenNav = [];
                        pageListToTree(this.dataList, childrenNav, 0);
                        this.data = childrenNav;
                        console.log("pageList__expandedRowKeys", this.expandedRowKeys)
                        this.expandedRowKeys = [...this.expandedRowKeys];
                        Object.assign(this.pagination, {
                            total
                        });
                    }
                })
                .catch(error => { });
        },
        Disable (item) {
            keyDisable({ id: item.id })
                .then(response => {
                    if (response.code === 200) {
                        this.$message.success("禁用成功");
                        //刷新 列表
                        this.PageList();
                    }
                })

        },
        Enable (item) {
            keyEnable({ id: item.id })
                .then(response => {
                    if (response.code === 200) {
                        this.$message.success("启用成功");
                        //刷新 列表
                        this.PageList();
                    }
                })

        },
        //获取 
        showFunction () {
            this.show = !this.show;
        },
        showModal (editItem) {
            console.log("editItem", editItem);
            this.editItem = { ...editItem };
            this.editModal = true;
        },
        hideModal () {
            this.editModal = false;
        },
        onSubmit () {
            //todo 检查数据格式（延迟处理）
            keySave(this.editItem)
                .then(response => {
                    if (response.code === 200) {
                        this.$message.success("保存成功");
                        //刷新 列表
                        this.PageList();
                        this.hideModal();
                    }
                })

        },
        onTableChange (pagination, filters, sorter) {
            Object.assign(this.postData, {
                "page.current": pagination.current,
                "page.size": pagination.pageSize
            });
            Object.assign(this.pagination, {
                current: pagination.current,
                pageSize: pagination.pageSize
            });
            this.PageList();
        },
        //查询 子集数据
        onTableExpand (expanded, record) {
            let { expandedRowKeys } = this;
            if (expanded) {
                expandedRowKeys.push(record.id);
            } else {
                expandedRowKeys.splice(expandedRowKeys.findIndex(item => item === record.id), 1);
            }
            // this.expandedRowKeys = [...expandedRowKeys];
            if (!expanded || this.haveExpandSet.has(record.id)) return false;
            const postData = {
                "page.current": 1,
                "page.size": 1000,
                parentId: record.id
            };
            PageList(postData)
                .then(response => {
                    console.log(`获取：${record.dictLabel}——的子集`, response);
                    if (response.code === 200) {
                        const { data } = response;
                        const { records } = data;

                        records.forEach(item => {
                            if (!this.dataKeySet.has(item.id)) {
                                item.key = item.id;
                                if (!item.treeLeaf) {
                                    item.children = [];
                                }
                                record.children.push(item);
                                this.dataList.push(item);
                                this.dataKeySet.add(item.id);
                            }
                        });
                        this.data = [...this.data];
                        // const childrenNav = [];
                        // pageListToTree(this.dataList, childrenNav, 0);
                        // console.log("childrenNav:",childrenNav);
                        // this.data = childrenNav;
                        this.haveExpandSet.add(record.id);
                    }
                })
                .catch(error => { });
        },
        reset () {
            this.postData = { ...basePostData };
        }
    },
    watch: {
        $route: function () {
            let { dictTypeId, dictName } = this.$route.params;
            Object.assign(this, {
                dictTypeId,
                dictName
            });
            const breadcrumbItem = [
                {
                    text: "首页",
                    to: "/",
                    icon: "nlyfont nly-icon-home-fill"
                },
                {
                    text: "系统管理",
                    to: "/system"
                },
                {
                    text: "字典管理(" + this.dictName + ")",
                    to: "/system/dictType/list",
                    active: true
                }
            ];
            this.breadcrumbItem = breadcrumbItem;

            this.reset();
            this.PageList();
        }
        // "editItem.menuIcon": function(newval, oldval) {
        //   console.log("editItem.menuIcon", newval);
        // },
        // treeData: function(newval, oldval) {
        //   console.log("treeData", newval);
        // }
    }
};
</script>
<style>
    /* .form-inline > label {
      justify-content: right !important;
    }
    .ant-radio-group > label{
       justify-content: left !important;
    }
    .ant-checkbox-group >label{
       justify-content: left !important;
    }
    .form-inline > .col {
      margin-bottom: 1.5rem !important;
    } */
</style>
